package com.shanling.shanlingcontroller.services;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;


import com.actions.ibluz.manager.BluzManagerData;
import com.chipsguide.lib.bluetooth.extend.devices.BluetoothDeviceSoundBoxManager;
import com.chipsguide.lib.bluetooth.managers.BluetoothDeviceManager;
import com.linkplay.lpvr.avslib.LPAVSManager;
import com.linkplay.lpvr.blelib.manager.LPAVSBTManager;
import com.linkplay.lpvr.lpvrbean.BaseDevice;
import com.linkplay.lpvr.lpvrbean.DeviceInformation;
import com.shanling.shanlingcontroller.CustomApplication;
import com.shanling.shanlingcontroller.R;
import com.shanling.shanlingcontroller.base.BaseAppManager;
import com.shanling.shanlingcontroller.bean.BluetoothState;
import com.shanling.shanlingcontroller.bean.Constants;
import com.shanling.shanlingcontroller.bean.EventCenter;

import com.shanling.shanlingcontroller.bean.MybluetoothDevice;


import com.shanling.shanlingcontroller.manager.DeviceMusicManager;
import com.shanling.shanlingcontroller.music.player.PlayManager;
import com.shanling.shanlingcontroller.receiver.A2DPConnectionStateReceiver;
import com.shanling.shanlingcontroller.receiver.BondStateReceiver;
import com.shanling.shanlingcontroller.services.csr.GAIABREDRProvider;
import com.shanling.shanlingcontroller.ui.activity.DeviceMusicActivity;
import com.shanling.shanlingcontroller.utils.PreferenceUtil;
import com.shanling.shanlingcontroller.utils.ToastUtils;


import org.greenrobot.eventbus.EventBus;
import org.litepal.LitePal;

import java.util.Arrays;
import java.util.List;


public class BluetoothStateService extends Service {
    private PreferenceUtil util;
    private CustomApplication customApplication;
    private BluetoothDeviceManager bluetoothDeviceManager;
    private Myreceiver myreceiver;
    private A2DPConnectionStateReceiver a2DPConnectionStateReceiver;
    private GAIABREDRProvider mGAIABREDRProvider;
    private BondStateReceiver bondStateReceiver;

    public BluetoothStateService() {
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        startForeground(this);
        customApplication = CustomApplication.getInstance();
        bluetoothDeviceManager = customApplication.getBluetoothDeviceManager();
        util = PreferenceUtil.getInstance(customApplication);
        myreceiver = new Myreceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(LPAVSBTManager.ACTION_STATE_CHANGED);
        filter.addAction(LPAVSBTManager.ACTION_BLE_PASS);
        filter.setPriority(2147483647);
        LocalBroadcastManager.getInstance(this).registerReceiver(myreceiver, filter);
        initBluetoothListener();
        initA2DPReceiver();
        initBREProvider();
        initBondReceiver();
    }

    private void initBondReceiver() {
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        bondStateReceiver = new BondStateReceiver();
        registerReceiver(bondStateReceiver, filter);
    }

    private void initBREProvider() {
        if (mGAIABREDRProvider == null) {
            mGAIABREDRProvider = new GAIABREDRProvider(
                    (BluetoothManager) customApplication.getSystemService(BLUETOOTH_SERVICE));
        }
        customApplication.setmGAIABREDRProvider(mGAIABREDRProvider);
    }

    private void startForeground(Service context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
            PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);
            Notification.Builder builder = (new Notification.Builder(context, "shanling"))
                    .setVisibility(Notification.VISIBILITY_PUBLIC)
                    .setOngoing(true)
                    .setContentIntent(pIntent)
                    .setContentTitle(context.getResources().getString(R.string.app_name))
                    .setContentText(context.getResources().getString(R.string.service_running))
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setColor(0xffCAB487);
            Notification notification = builder.build();
            context.startForeground(101, notification);
        }
    }

    public void initA2DPReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
        a2DPConnectionStateReceiver = new A2DPConnectionStateReceiver();
        registerReceiver(a2DPConnectionStateReceiver, filter);
    }

    private void initBluetoothListener() {
        if (bluetoothDeviceManager != null) {
            bluetoothDeviceManager.setOnBluetoothDeviceConnectionStateChangedListener(connectionStateListener);
            bluetoothDeviceManager.setOnBluetoothDeviceManagerReadyListener(onManagerReadyListener);
            bluetoothDeviceManager.setOnBluetoothDeviceGlobalUIChangedListener(globalUIChangedListener);

        }
    }

    /**
     * 蓝牙连接回调
     */
    private BluetoothDeviceManager.OnBluetoothDeviceConnectionStateChangedListener connectionStateListener = new BluetoothDeviceManager.OnBluetoothDeviceConnectionStateChangedListener() {
        @Override
        public void onBluetoothDeviceConnectionStateChanged(final BluetoothDevice bluetoothDevice, int state) {
            if (util.getBleType() != 2) {
                return;
            }
            Log.e("weiyu", "蓝牙状态" + state);
            switch (state) {
                case Constants.CONNECTED:
                    customApplication.setConnected(true);
                    util.setBleName(bluetoothDevice.getName());
                    List<MybluetoothDevice> mybluetoothDevices = LitePal.findAll(MybluetoothDevice.class);
                    MybluetoothDevice mybluetoothDevice = new MybluetoothDevice();
                    mybluetoothDevice.setType(2);
                    util.setBleType(2);
                    util.setBleMac(bluetoothDevice.getAddress());
                    mybluetoothDevice.setName(bluetoothDevice.getName());
                    mybluetoothDevice.setBluetoothDevice(bluetoothDevice);
                    mybluetoothDevice.setMac(bluetoothDevice.getAddress());
                    if (!mybluetoothDevices.contains(mybluetoothDevice)) {
                        mybluetoothDevice.save();
                    }
                    ToastUtils.showToast(customApplication, R.string.bluetooth_connected);
                    EventBus.getDefault().post(new EventCenter<>(Constants.BLUETOOTH_STATE, new BluetoothState(Constants.CONNECTED)));
                    break;
                case Constants.DISCONNECTED:
                    customApplication.setConnected(false);
                    BaseAppManager.getInstance().finishActivityclass(DeviceMusicActivity.class);
                    ToastUtils.showLongToast(customApplication, R.string.bluetooth_disconnected);
                    EventBus.getDefault().post(new EventCenter<>(Constants.BLUETOOTH_STATE, new BluetoothState(Constants.DISCONNECTED)));
                    break;
            }
        }
    };
    /**
     * 蓝牙准备好回调
     * 当蓝牙连接设备后就会走这个回调监听
     */
    private BluetoothDeviceManager.OnBluetoothDeviceManagerReadyListener onManagerReadyListener = new BluetoothDeviceManager.OnBluetoothDeviceManagerReadyListener() {
        @Override
        public void onBluetoothDeviceManagerReady() {
            Log.e("weiyu", "BluetoothStateService--->onBluetoothDeviceManagerReady");
            if (util.getBleType() == 2) {
                String version = bluetoothDeviceManager.getFirmwareVersion();
                Log.e("weiyu", "版本" + version);
                MybluetoothDevice mybluetoothDevice = new MybluetoothDevice();
                mybluetoothDevice.setCurrent_Version(version);
                mybluetoothDevice.updateAll("mac = ?", util.getBleMac());
            }
        }
    };

    private BluetoothDeviceManager.OnBluetoothDeviceGlobalUIChangedListener globalUIChangedListener = new BluetoothDeviceManager.OnBluetoothDeviceGlobalUIChangedListener() {
        @Override
        public void onBluetoothDeviceVolumeChanged(int i, boolean b) {

        }

        @Override
        public void onBluetoothDeviceModeChanged(int mode) {
            Log.e("MISS", " onBluetoothDeviceModeChanged ----- " + mode);
            DeviceMusicManager.getInstance().getDeviceMode(mode);
            if (mode == BluetoothDeviceManager.Mode.CARD) {
                PlayManager.pause();
                DeviceMusicManager.getInstance().setOnBluetoothDeviceCardMusicManagerReadyListener();
            } else {
                DeviceMusicManager.getInstance().destroy();
            }
        }

        @Override
        public void onBluetoothDeviceEQChanged(int i) {

        }

        @Override
        public void onBluetoothDeviceEQChanged(int i, int[] ints) {

        }

        @Override
        public void onBluetoothDeviceBatteryChanged(int i, boolean b) {

        }

        @Override
        public void onBluetoothDeviceNameChanged(boolean b) {

        }

        @Override
        public void onBluetoothDeviceNameChanged(int i, boolean b) {

        }

        @Override
        public void onBluetoothDeviceVoltageChanged(int i) {

        }

        @Override
        public void onBluetoothDeviceKeyChanged(int i, int i1) {

        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopForeground(true);// 停止前台服务--参数：表示是否移除之前的通知
        LocalBroadcastManager.getInstance(this).unregisterReceiver(myreceiver);
        unregisterReceiver(a2DPConnectionStateReceiver);
        unregisterReceiver(bondStateReceiver);
    }

    public class Myreceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case LPAVSBTManager.ACTION_STATE_CHANGED:
                    if (util.getBleType() == 1) {
                        int i = intent.getIntExtra("com.linkplay.lpvr.blelib.manager.BT_STATE", -1);
                        onStateChange(i);
                        //  Log.e("weiyu", "蓝牙状态" + i);
                    }
                    break;
                case LPAVSBTManager.ACTION_BLE_PASS:
                    byte[] datas = intent.getByteArrayExtra(LPAVSBTManager.BLE_PASS);
                    Log.e("weiyu", "数据 ---- " + Arrays.toString(datas));
                    EventBus.getDefault().post(new EventCenter<>(Constants.EQ_DATA, datas));
                    break;

            }
        }
    }

    public void onStateChange(int state) {
        switch (state) {
            case 0://    LP_BLE_STATE_CONNECTED	已连接 0
                BaseDevice validDevice = LPAVSManager.getInstance(customApplication).getBtManager().getValidDevice();
                if (validDevice != null && validDevice.getName().contains("US1i")) {
                    customApplication.setConnected(true);
                    EventBus.getDefault().post(new EventCenter<>(Constants.BLUETOOTH_STATE, new BluetoothState(Constants.CONNECTED)));
                    util.setBleMac(validDevice.getAddress());
                    util.setBleName(validDevice.getName());
                    util.setBleType(1);
                    BluetoothDevice bluetoothDevice = validDevice.getBluetoothDevice();
                    MybluetoothDevice mycheckDevice = new MybluetoothDevice(
                            bluetoothDevice, 1, validDevice.getName(), validDevice.getAddress());
                    DeviceInformation deviceInformation = LPAVSManager.getInstance(customApplication).getBtManager().getDeviceInformation();
                    if (deviceInformation != null) {
                        String subVersion = deviceInformation.getSubVersion();
                        mycheckDevice.setCurrent_Version(subVersion);
                    }
                    List<MybluetoothDevice> mybluetoothDevices = LitePal.findAll(MybluetoothDevice.class);
                    if (!mybluetoothDevices.contains(mycheckDevice)) {
                        mycheckDevice.save();
                    }
                    Log.e("weiyu", "保存数据" + "mac" + mycheckDevice.getMac());

                }
                break;
            case 1://    LP_BLE_STATE_NOT_CONNECTED	未连接 1
                customApplication.setConnected(false);
                EventBus.getDefault().post(new EventCenter<>(Constants.BLUETOOTH_STATE, new BluetoothState(Constants.DISCONNECTED)));
                break;
            case 3://    LP_BLE_STATE_INVALID	当前连接的设备不合法 3
                customApplication.setConnected(false);
                EventBus.getDefault().post(new EventCenter<>(Constants.BLUETOOTH_STATE, new BluetoothState(Constants.DISCONNECTED)));
                break;
            case 4://    LP_BLE_STATE_NOBT	未连接蓝牙 4
                customApplication.setConnected(false);
                EventBus.getDefault().post(new EventCenter<>(Constants.BLUETOOTH_STATE, new BluetoothState(Constants.DISCONNECTED)));
                break;
            case 5://    LP_BLE_STATE_BT_UNPOWER	手机未打开蓝牙 5
                customApplication.setConnected(false);
                EventBus.getDefault().post(new EventCenter<>(Constants.BLUETOOTH_STATE, new BluetoothState(Constants.DISCONNECTED)));
                break;
            case 6://    LP_BLE_STATE_CONNECT_TIMEOUT	连接蓝牙超时 6
                customApplication.setConnected(false);
                EventBus.getDefault().post(new EventCenter<>(Constants.BLUETOOTH_STATE, new BluetoothState(Constants.DISCONNECTED)));
                break;
        }
    }
}
